﻿using CommunicationCore.OpcUaClient;
using Opc.Ua;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace OpcTest
{
    public class KepWareOpcService : IKepwareOpcService
    {

        private OpcUaSimpleClient opcClent;
        private readonly OpcServerConfiguration m_ServerConfig;
        public KepWareOpcService(OpcServerConfiguration config)
        {
            m_ServerConfig = config;
            opcClent = new OpcUaSimpleClient(m_ServerConfig.ClientName, m_ServerConfig.UseConfiguration,
                m_ServerConfig.UserName, m_ServerConfig.Password, m_ServerConfig.SecerityPolic);
            //opcClent = new OpcUaSimpleClient();
        }



        /// <summary>
        /// 异步连接
        /// </summary>
        /// <returns></returns>
        public async Task Connect()
        {
            await opcClent.Connect(m_ServerConfig.ServerUrl);
        }

        /// <summary>
        /// 同步连接
        /// </summary>
        public void DoConnect()
        {
            try
            {
                opcClent.Connect(m_ServerConfig.ServerUrl).Wait();
                Console.WriteLine("connect complete");
            }
            catch(Exception ex)
            {
                Console.WriteLine("connect failed  "+ ex.Message);
            }
            
            
        }


        //nodeId: ns=2;s=siemens.1212.clean
        //browsename: 2:clean
        //displayname:clean

        public void BrowsNode()
        {
            //找出 用户自定义通道
            ReferenceDescriptionCollection channels = opcClent.FoundUserDefineChannels();

            foreach (var c in channels)
            {
                Console.WriteLine(c.DisplayName.Text);
                ReferenceDescriptionCollection devices = opcClent.FoundUserDefineNodes(c);

                foreach (var d in devices)
                {
                    Console.WriteLine(" -"+ d.DisplayName.Text);
                    ReferenceDescriptionCollection variables = opcClent.FoundUserDefineVariables(d);
                    foreach(var v in variables)
                    {
                        int type = opcClent.GetVariableDataType(v, Attributes.DataType);


                        Console.WriteLine("  -" + v.NodeId.ToString() + "   "+ type);
                    }

                }

            }


        }

        public void CreateSubscription()
        {
            throw new NotImplementedException();
        }

        public void Disconnect()
        {
            opcClent.Disconnect();
        }
    }
}
